//
//  JobCollectionViewController.m
//  CYWFrame
//
//  Created by 于顺燊 on 2018/10/22.
//  Copyright © 2018年 Macx. All rights reserved.
//

#import "JobCollectionViewController.h"
#import "JobCollectionTableViewCell.h"
#import "JobInfoForRecruitIndex.h"
#import "ResumeCollectionTableViewCell.h"
#import "JobDetailViewController.h"
#import "PreviewResumeViewController.h"

@interface JobCollectionViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (strong, nonatomic) UITableView *tableView;
@property (strong ,nonatomic) NSMutableArray *infoArr;
@property (strong ,nonatomic) NSMutableArray *selectedIdArr;
@property NSInteger page;
@property (assign, nonatomic) BOOL isAllSelected;

@end

@implementation JobCollectionViewController

- (void)viewDidLoad {
	[super viewDidLoad];
	[self createUI];
	[self getInfoList];
	[self refreshData];
	// Do any additional setup after loading the view.
}

- (void)createUI {
	NSInteger role = [GetUserDefaule(USERINFO)[@"role"] integerValue];
	_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-50) style:UITableViewStylePlain];
	
	if (role == 5 || role == 6) {
		self.navigationItem.title = @"人才收藏";
		[_tableView registerNib:[UINib nibWithNibName:@"ResumeCollectionTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
	}
	else {
		self.navigationItem.title = @"岗位收藏";
		[_tableView registerNib:[UINib nibWithNibName:@"JobCollectionTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
	}
	_tableView.dataSource = self;
	_tableView.delegate = self;
	_tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
	_tableView.backgroundColor = UISeparatedColorRGB;
	[self.view addSubview:_tableView];
	
	UIButton *cancelCollectedBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-64-50, SW(2), 50)];
	[cancelCollectedBtn setTitle:@"取消收藏" forState:UIControlStateNormal];
	cancelCollectedBtn.backgroundColor = kLightGrayColor;
	[cancelCollectedBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
	[cancelCollectedBtn addTarget:self action:@selector(cancelCollect) forControlEvents:UIControlEventTouchUpInside];
	UIButton *deliverBtn = [[UIButton alloc] initWithFrame:CGRectMake(cancelCollectedBtn.width, cancelCollectedBtn.y, SW(2), 50)];
	if (role == 5 || role == 6) {
		[deliverBtn setTitle:@"一键邀约" forState:UIControlStateNormal];
	}
	else {
		[deliverBtn setTitle:@"一键投递" forState:UIControlStateNormal];
	}
	[deliverBtn addTarget:self action:@selector(deliver) forControlEvents:UIControlEventTouchUpInside];
	deliverBtn.backgroundColor = UIMainColorRGB;
	[deliverBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
	
	[self.view addSubview:cancelCollectedBtn];
	[self.view addSubview:deliverBtn];
	
	UIButton *selectAllBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	[selectAllBtn setTitle:@"全选" forState:UIControlStateNormal];
	[selectAllBtn addActionWithblock:^{
		for (JobInfoForRecruitIndex *model in self.infoArr){
			if (self.isAllSelected == NO) {
				model.isCollectionCellSelected = YES;
			}
			else {
				model.isCollectionCellSelected = NO;
			}
		}
		self.isAllSelected = !self.isAllSelected;
		[self.tableView reloadData];
	}];
	
	UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:selectAllBtn];
	self.navigationItem.rightBarButtonItem = rightItem;
	
}
#pragma mark ==========UITableView==========
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	NSInteger role = [GetUserDefaule(USERINFO)[@"role"] integerValue];
	if (role == 5 || role == 6) {
		ResumeCollectionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
		JobInfoForRecruitIndex *model = self.infoArr[indexPath.row];
		cell.jobInfo = model;
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		if (model.isCollectionCellSelected) {
			[cell.selectBtn setSelected:YES];
		}
		else {
			[cell.selectBtn setSelected:NO];
		}
		[cell.selectBtn addActionWithblock:^{
			[cell.selectBtn setSelected:!cell.selectBtn.isSelected];
			model.isCollectionCellSelected = cell.selectBtn.isSelected;
		}];
		return cell;
	}
	else {
		JobCollectionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
		JobInfoForRecruitIndex *model = self.infoArr[indexPath.row];
		cell.jobInfo = model;
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		if (model.isCollectionCellSelected) {
			[cell.selectBtn setSelected:YES];
		}
		else {
			[cell.selectBtn setSelected:NO];
		}
		[cell.selectBtn addActionWithblock:^{
			[cell.selectBtn setSelected:!cell.selectBtn.isSelected];
			model.isCollectionCellSelected = cell.selectBtn.isSelected;
		}];
		return cell;
	}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	NSLog(@"the number is %ld", self.infoArr.count);
	return self.infoArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
	return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	NSInteger role = [GetUserDefaule(USERINFO)[@"role"] integerValue];
	if (role == 5 || role == 6) {
		return 157;
	}
	else {
		return 147;
	}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	NSString *role = GetUserDefaule(USERINFO)[@"role"];
	if ([role isEqualToString:@"1"] || [role isEqualToString:@"3"]) {
		[self presentViewController:[LZCTools alertMessage:@"您没有查看详情的权限"] animated:YES completion:nil];
	}
	if ([role integerValue] == 0) {
		[self presentViewController:[LZCTools alertMessage:@"请先登录"] animated:YES completion:nil];
	}
	if ([role isEqualToString:@"5"] ||
		[role isEqualToString:@"6"]) {
		PreviewResumeViewController *resumeVC = [[PreviewResumeViewController alloc] init];
		JobInfoForRecruitIndex *jobInfo = self.infoArr[indexPath.row];
		resumeVC.resumeId = jobInfo.resume_id;
		resumeVC.shouldShowInviteBtn = 1;
		[self.navigationController pushViewController:resumeVC animated:YES];
		
	}
	else
	{
		JobDetailViewController *detail = [[JobDetailViewController alloc] init];
		JobInfoForRecruitIndex *jobInfo = self.infoArr[indexPath.row];
		detail.position_id = jobInfo.position_id;
		detail.shouldHideDeliverBtn = 0;
		[self.navigationController pushViewController:detail animated:YES];
		
	}
}

- (void)refreshData {
	__weak typeof (self) weakSelf = self;
	
	_tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
		NSLog(@"下拉刷新");
		weakSelf.page = 1;
		[weakSelf getInfoList];
	}];
	
	/*
	_tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
		NSLog(@"上拉加载");
		weakSelf.page++;
		[weakSelf getInfoList];
	}];
	 */
	
}

- (void)getInfoList {
	
	NSString *url;
	NSInteger role = [GetUserDefaule(USERINFO)[@"role"] integerValue];
	if (role == 5 || role == 6) {
		url = APIResumeCollectionList;
	}
	else {
		url = APIJobCollectionList;
	}
	[[NetworkTool sharedTool] requestWithName:@"获取岗位/人才收藏列表" URLString:url parameters:nil method:@"POST" callBack:^(id responseObject) {
		
		NSArray *arr = responseObject[@"data"];
		[self.infoArr removeAllObjects];
		if (self.page == 1) {
			[self.infoArr removeAllObjects];
		}
		for (NSDictionary *dict in arr) {
			
			JobInfoForRecruitIndex *model = [[JobInfoForRecruitIndex alloc] init];
			[model setValuesForKeysWithDictionary:dict];
			[self.infoArr addObject:model];
		}
		[self.tableView reloadData];
		dispatch_async(dispatch_get_main_queue(), ^{
			[self.tableView reloadData];
			[self.tableView.mj_header endRefreshing];
			[self.tableView.mj_footer endRefreshing];
		});
	}];
}

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
	// Dispose of any resources that can be recreated.
}

- (NSMutableArray *)infoArr
{
	if (!_infoArr) {
		_infoArr = [[NSMutableArray alloc] init];
	}
	return _infoArr;
}

- (NSMutableArray *)selectedIdArr {
	if (!_selectedIdArr) {
		_selectedIdArr = [[NSMutableArray alloc] init];
	}
	return _selectedIdArr;
}

- (void)cancelCollect {
	
	NSDictionary *dict;
	NSInteger role = [GetUserDefaule(USERINFO)[@"role"] integerValue];
	if (role == 5 || role == 6) {
		NSString *resumeIdStr = @"";
		NSMutableArray *selectedResumeIdArr = [[NSMutableArray alloc] init];
		for (JobInfoForRecruitIndex *model in self.infoArr) {
			if (model.isCollectionCellSelected) {
				[selectedResumeIdArr addObject:model.resume_id];
			}
			resumeIdStr = [selectedResumeIdArr componentsJoinedByString:@","];
		}
		if ([resumeIdStr isEqualToString:@""]) {
			[LZCTools HUDMessage:@"请至少选择一位人才进行操作" delay:1.0];
			return;
		}
		dict = @{@"type":@"1",
				 @"resume_ids":resumeIdStr
				 };
	}
	else {
		NSString *positionIdStr = @"";
		NSMutableArray *selectedPositionIdArr = [[NSMutableArray alloc] init];
		for (JobInfoForRecruitIndex *model in self.infoArr) {
			if (model.isCollectionCellSelected) {
				[selectedPositionIdArr addObject:model.position_id];
			}
			positionIdStr = [selectedPositionIdArr componentsJoinedByString:@","];
		}
		if ([positionIdStr isEqualToString:@""]) {
			[LZCTools HUDMessage:@"请至少选择一个职位进行操作" delay:1.0];
			return;
		}
		dict = @{@"type":@"2",
				 @"position_ids":positionIdStr
				 };
	}
	UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定取消收藏？" message:nil preferredStyle:UIAlertControllerStyleAlert];
	[alert addAction:[UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
	}]];
	[alert addAction:[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
		
		[[NetworkTool sharedTool] requestWithName:@"批量取消收藏" URLString:APICancelCollectJobOrResume parameters:dict method:@"POST" callBack:^(id responseObject) {
			[self getInfoList];
		}];
	}]];
	[self presentViewController:alert animated:YES completion:nil];
}

- (void)deliver {
	NSDictionary *dict;
	NSString *url;
	NSInteger role = [GetUserDefaule(USERINFO)[@"role"] integerValue];
	if (role == 5 || role == 6) {
		NSString *resumeIdStr = @"";
		NSMutableArray *selectedResumeIdArr = [[NSMutableArray alloc] init];
		for (JobInfoForRecruitIndex *model in self.infoArr) {
			if (model.isCollectionCellSelected) {
				NSLog(@"id is %@", model.resume_id);
				[selectedResumeIdArr addObject:model.resume_id];
			}
			resumeIdStr = [selectedResumeIdArr componentsJoinedByString:@","];
		}
		if ([resumeIdStr isEqualToString:@""]) {
			[LZCTools HUDMessage:@"请至少选择一位人才进行操作" delay:1.0];
			return;
		}
		url = APIMakeInvitation;
		dict = @{
				 @"resume_id":resumeIdStr
				 };
	}
	else {
		NSString *positionIdStr = @"";
		NSMutableArray *selectedPositionIdArr = [[NSMutableArray alloc] init];
		
		for (JobInfoForRecruitIndex *model in self.infoArr) {
			if (model.isCollectionCellSelected) {
				NSLog(@"id is %@", model.position_id);
				NSLog(@"positionName is %@", model.title);
				[selectedPositionIdArr addObject:model.position_id];
			}
			positionIdStr = [selectedPositionIdArr componentsJoinedByString:@","];
		}
		if ([positionIdStr isEqualToString:@""]) {
			[LZCTools HUDMessage:@"请至少选择一个职位进行操作" delay:1.0];
			return;
		}
		url = APISendResume;
		dict = @{
				 @"position_id":positionIdStr
				 };
	}
	UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定进行投递？" message:nil preferredStyle:UIAlertControllerStyleAlert];
	[alert addAction:[UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
	}]];
	[alert addAction:[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
		[[NetworkTool sharedTool] requestWithName:@"批量投递" URLString:url parameters:dict method:@"POST" callBack:^(id responseObject) {
			[self presentViewController:[LZCTools alertMessage:@"操作成功"] animated:YES completion:nil];
			[self getInfoList];
		}];
	}]];
	[self presentViewController:alert animated:YES completion:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
